
import React, { memo, useEffect, useRef, useState } from 'react';
import {
  ConfigProvider,
  Divider,
  Table,
  Modal,
  Button,
  Form,
  Input,
  Popconfirm,
  Space,
  Dropdown,
  message,
  Drawer,
  Menu,
  Select,
  Descriptions,
  Col,
  Row
} from 'antd';
import { TableRowSelection } from 'antd/es/table/interface';
import { ProForm } from '@/base-ui';
import DivWrapper from './style';
import zhCN from 'antd/es/locale/zh_CN';
import http from '@/services/request';
import {
  PageSearchConfig,
  SearchSelector,
  DataType,
  UseSearch
} from './config';
const { Option } = Select;

//form
// form这里需要根据你们后端接口的字段去改，改动一下name，label rule这些属性
const NewForm = (props: any) => {
  return (
    <Form
      ref={props.newref}
      layout={'vertical'}
      style={{
        minHeight: '100%',
        flex: 1,
        overflow: 'auto',
        width: '100%',
        overflowX: 'hidden'
      }}
    >
      <Row>
        <Col xs={{ span: 5, offset: 2 }} lg={{ span: 8, offset: 2 }}>
          {/* <Form.Item
            label="车辆id"
            name="id"
            rules={[{ required: true, message: '请输入车辆id' }]}
          >
            <Input />
          </Form.Item> */}
          <Form.Item
            label="车库id"
            name="garageId"
            rules={[{ required: true, message: '请输入车库id' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="车辆品牌"
            name="carBrand"
            rules={[{ required: true, message: '请输入车辆品牌' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="车辆类型"
            name="carType"
            rules={[{ required: true, message: '请输入车辆类型' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="车牌号"
            name="licensePlateNumber"
            rules={[{ required: true, message: '请输入车牌号' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="车辆颜色"
            name="carColor"
            rules={[{ required: true, message: '请输入车辆颜色' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="可承载货物重量(kg)"
            name="carryFreightWeight"
            rules={[{ required: true, message: '请输入可承载货物重量(kg)' }]}
          >
            <Input />
          </Form.Item>
        </Col>
        <Col xs={{ span: 5, offset: 2 }} lg={{ span: 8, offset: 2 }}>
          <Form.Item
            name="operationCertificateNumber"
            label="运营证号"
            rules={[{ required: true, message: '请输入运营证号' }]}
          >
            <Input />
          </Form.Item>
          {/* <Form.Item
            name="carStatus"
            label="调试状态"
            rules={[{ required: true, message: '请选择调试状态' }]}
          >
            <Input />
          </Form.Item> */}
          <Form.Item
            name="carStatus"
            label="调试状态"
            rules={[{ required: true, message: '请选择调试状态' }]}
          >
            <Select>
              <Option value="空闲">空闲</Option>
              <Option value="忙碌">忙碌</Option>
              <Option value="维修">维修</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="remark"
            label="备注"
            rules={[{ required: false, message: '请输入备注' }]}
          >
            <Input />
          </Form.Item>
        </Col>
      </Row>
    </Form>
  );
};

const Invoice = memo(() => {
  //更多功能定位id
  const [drawerId, setDrawerID]: any = useState({});
  //抽屉开关
  const [DrawerVisible, setDrawerVisible] = useState(false);
  //复选框批量删除

  //是否新增
  const [edited, setedited]: any = useState('');
  //高级检索
  const [isMoreSearchShow, setisMoreSearchShow]: any = useState(false);
  const newref: any = useRef();
  const [dataSource, setdataSource]: any = useState([]);
  const [searchMore, setSearchMore] = useState(false);

  // 控制对话框显示（新增）
  const [addModalVisible, setAddModalVisible] = useState(false);

  useEffect(() => {
    http.get('/logistics/carLogistics/get/1/10').then((res) => {
      setdataSource(res.data.records);
    });
  }, []);

  //  checkDeleteArray 存着要删除的表格行，以便发送到后端
  let checkDeleteArray: any = [];

  const rowSelection: TableRowSelection<DataType> = {
    // 控制复选框，一个一个选择
    onSelect: (record) => {
      checkDeleteArray = [];
      checkDeleteArray.push(record.id);
    },

    // 控制全选功能
    onSelectAll: (selected, selectedRows, changeRows) => {
      checkDeleteArray = [];
      changeRows.forEach((item) => {
        checkDeleteArray.push(item.id);
      });
    },
    selections: [Table.SELECTION_ALL, Table.SELECTION_NONE]
  };

  //按钮组
  const Buttongroup = (props: any) => {
    return (
      <div style={{ marginBottom: 10, float: 'left' }}>
        <Button
          type="primary"
          onClick={() => props.add()}
          style={{ marginRight: 10 }}
        >
          新增信息
        </Button>
        <Button
          danger
          onClick={() => {
            props.checkIt();
          }}
          style={{ marginRight: 10 }}
        >
          批量删除
        </Button>
      </div>
    );
  };

  // 这是批量删除用于删除选择的那些数据
  const checkIt = () => {
    http({
      url: `/logistics/carLogistics/batchDelete`,
      method: 'delete',
      data: JSON.stringify(checkDeleteArray),
      headers: { 'Content-Type': 'application/json' }
    }).then(() => {
      http.get('/logistics/carLogistics/get/1/10').then((res) => {
        setdataSource(res.data.records);
      });
    });
  };

  //导出
  const exported = () => {
    http({
      method: 'get',
      url: '/server/dailySlaughter/export',
      data: JSON.stringify([1, 4]),
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json'
      }
    }).then((res: any) => {
      const blob = new Blob([res.data], {
        // res 为后台返回数据
        type: 'application/vnd.ms-excel;charset=utf-8' // 导出数据生成excel的格式设置
      });
      if ('download' in document.createElement('a')) {
        // 非IE下载
        const elink = document.createElement('a');
        elink.download = Date.now() + `.xlsx`;
        elink.style.display = 'none';
        elink.target = '_blank';
        elink.href = window.URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
      }
    });
  };

  // 对话框确认
  const handleAddModalOk = () => {
    setAddModalVisible(false);
    // 修改操作
    if (edited) {
      const newedited = newref.current.getFieldsValue();
      http
        .put(`/logistics/carLogistics/update/${edited.id}`, {
          ...newedited
        })
        .then(() => {
          http.get('/logistics/carLogistics/get/1/10').then((res) => {
            setdataSource(res.data.records);
          });
        });
      setedited(null);
      return;
    }

    //id不在--就是新增
    const addData = newref.current.getFieldsValue();
    const {
      garageId,
      id,
      carBrand,
      carColor,
      carModel,
      carStatus,
      carType,
      carryFreightWeight,
      licensePlateNumber,
      operationCertificateNumber,
      remark,
    } = addData;

    http
      .post('/logistics/carLogistics/save', {
        garageId,
        id,
        carBrand,
        carColor,
        carModel,
        carStatus,
        carType,
        carryFreightWeight,
        licensePlateNumber,
        operationCertificateNumber,
        remark,
      })
      .then(() => {
        http.get('/logistics/carLogistics/get/1/10').then((res) => {
          setdataSource(res.data.records);
        });
      })
      .catch((error) => {
        // eslint-disable-next-line no-console
        console.log(error);
      });
  };

  //编辑
  const edit = (id: any) => {
    setAddModalVisible(true);
    //这里必须单单setField..会报错："表单还没挂载调用了setFieldsValue",应该用异步，设一个定时器
    setTimeout(() => {
      newref.current.setFieldsValue({
        ...id
      });
      setedited(id);
    }, 0);
  };

  // 对话框取消
  const handleAddModalCancel = () => {
    setAddModalVisible(false);
  };
  const add = () => {
    setTimeout(() => {
      newref.current.setFieldsValue({
        // 此处重置新增的输入框
        garageId: "1575856020293439490",
        id:"111",
        carBrand: "",
        carColor: "",
        carModel: "",
        carStatus: "空闲",
        carType: "",
        carryFreightWeight: "",
        licensePlateNumber: "",
        operationCertificateNumber: "",
        remark: ""
      });
    });
    setAddModalVisible(true);
  };

  const indexTable = {
    pagination: {
      //每页10条项目
      defaultPageSize: 10,
      //自定义每页显示数目
      showSizeChanger: true,
      //当前的页数和大小
      onShowSizeChange: (current: any, pageSize: any) => {},
      //自定义每页显示项目的选项
      pageSizeOptions: ['1', '2', '3', '4', '5', '6', '8', '10'],

      // 输入指定页码跳页
      showQuickJumper: true,
      //跳页之后的回调函数
      onShowQuickJump: (page: any) => {},
      //全部项目数（最好可以用变量表示，与实际项目数关联）
      total: dataSource?.length,
      // 改变的回调函数
      onChange: (page: any) => {}
    }
  };

  const FormColumns: any = [
      // {
      //   title: '车辆id',
      //   dataIndex: 'id',
      //   key: 'id',
      //   width: 150
      // },
      // {
      //   title: '车库id',
      //   dataIndex: 'garageId',
      //   key: 'garageId',
      //   width: 150
      // },
      {
        title: '车辆品牌',
        dataIndex: 'carBrand',
        key: 'carBrand',
        width: 150
      },
      {
        title: '车辆类型',
        dataIndex: 'carType',
        key: 'carType',
        width: 150,
      },

      {
        title: '车牌号',
        dataIndex: 'licensePlateNumber',
        key: 'licensePlateNumber',
        width: 150
      },
      {
        title: '车辆颜色',
        dataIndex: 'carColor',
        key: 'carColor',
        width: 150,
      },
      {
        title: '可承载货物重量(kg)',
        dataIndex: 'carryFreightWeight',
        key: 'carryFreightWeight',
        width: 150
      },
      {
        title: '运营证号',
        dataIndex: 'operationCertificateNumber',
        key: 'operationCertificateNumber',
        width: 150
      },
      {
        title: '车辆状态',
        dataIndex: 'carStatus',
        key: 'carStatus',
        width: 150,
        //
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        width: 150
      },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action',
      width: 150,
      render: (_: any, record: any) => (
        <Space>
          <a onClick={() => edit(record)}>编辑</a>
          <Popconfirm
            title="确定删除?"
            okText="确认"
            cancelText="取消"
            onConfirm={() => {
              http
                .delete(`/logistics/carLogistics/delete/${record.id}`)
                .then(() => {
                  const newData = dataSource.filter(
                    (item: { id: any }) => item.id !== record.id
                  );
                  setdataSource(newData);
                });
            }}
          >
            <a style={{ color: '#ff4d4f' }}>删除</a>
          </Popconfirm>
          <Dropdown overlay={menu(record)}>
            <a
              onClick={(e) => {
                e.preventDefault();
              }}
            >
              ···
            </a>
          </Dropdown>
        </Space>
      ),
      fixed: 'right'
    }
  ];

  const menu = (item: any) => (
    <Menu
      items={[
        {
          key: 0,
          label: (
            <Button
              type="primary"
              onClick={() => {
                showDrawer(item);
              }}
            >
              详情
            </Button>
          )
        },
        {
          key: 2,
          label: (
            <Button
              onClick={function () {
                window.print();
              }}
            >
              打印
            </Button>
          )
        }
      ]}
    />
  );

  // 高级检索的函数
  const onFinish = (form: any) => {
    // 发送请
    http.post('/logistics/carLogistics/get', form).then((res: any) => {
      if (res.statusCode !== 20000) {
        return message.error('查询失败');
      }
      const data = res.data || [];
      setdataSource(data);
    });
  };
  //详情--抽屉
  const showDrawer = (data: any) => {
    setDrawerVisible(true);
    http.get(`/logistics/carLogistics/get/${data.id}`).then((res) => {
      setDrawerID(res.data);
    });
  };

  const onDraweClose = () => {
    setDrawerVisible(false);
  };

  return (
    <DivWrapper>
      {searchMore && (
        <div>
          <ProForm formItems={PageSearchConfig} onFinish={onFinish} />
          <Divider style={{ margin: '10px 0 20px' }} />
        </div>
      )}
      <Buttongroup
        checkIt={() => checkIt()}
        add={() => add()}
        exported={() => exported()}
      />
      <UseSearch
        setisMoreSearchShow={(e: any) => {
          setisMoreSearchShow(e);
        }}
        isMoreSearchShow={isMoreSearchShow}
        setsearchMore={(e: boolean) => setSearchMore(e)}
      />
      <SearchSelector dataSource={(e: any) => setdataSource(e)} />
      <ConfigProvider locale={zhCN}>
        <Table
          dataSource={dataSource || []}
          columns={FormColumns}
          scroll={{ x: 1300 }}
          pagination={indexTable.pagination}
          // rowKey={(i) => i.id}
          rowKey={(record) => record.id} //checkbox里，这里可以一行一行的选择，有唯一标识
          rowSelection={{
            type: 'checkbox',
            ...rowSelection
          }}
        />
      </ConfigProvider>
      <Drawer
        title="详情"
        placement="right"
        size="large"
        onClose={onDraweClose}
        visible={DrawerVisible}
      >
        <Descriptions
          title={`车牌号${drawerId.id}`}
          bordered
          style={{ width: '450px' }}
        >
          <Descriptions.Item label="车辆id">
            {drawerId.id}
          </Descriptions.Item>
          <Descriptions.Item label="车库id">
            {drawerId.garageId}
          </Descriptions.Item>
          <Descriptions.Item label="车辆类型">
            {drawerId.carType}
          </Descriptions.Item>
          <Descriptions.Item label="车牌号">
            {drawerId.licensePlateNumber}
          </Descriptions.Item>
          <Descriptions.Item label="车辆颜色">
            {drawerId.carColor}
          </Descriptions.Item>
          <Descriptions.Item label="可承载货物重量(kg)">
            {drawerId.carryFreightWeight}
          </Descriptions.Item>
          <Descriptions.Item label="运营证号">
            {drawerId.operationCertificateNumber}
          </Descriptions.Item>
          <Descriptions.Item label="调试状态">
            {drawerId.carStatus}
          </Descriptions.Item>
          <Descriptions.Item label="备注">
            {drawerId.remark}
          </Descriptions.Item>
        </Descriptions>
      </Drawer>
      <Modal
        width={'600px'}
        centered
        bodyStyle={{
          display: 'flex',
          flexDirection: 'column-reverse'
        }}
        title="新增信息"
        visible={addModalVisible}
        onOk={handleAddModalOk}
        onCancel={handleAddModalCancel}
      >
        <NewForm newref={newref} />
      </Modal>
    </DivWrapper>
  );
});
export default Invoice;

